package com.example.yuyin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;

public class FileUtils {
	private String SDCardRoot;

	public FileUtils() {
		//得到当前外部存储设备的目录
		SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
	}
	/**
	 * 在SD卡上创建文件
	 * 
	 * @throws IOException
	 */
	public File createFileInSDCard(String fileName,String dir) throws IOException {
		File file = new File(SDCardRoot+ dir + File.separator + fileName);
		System.out.println("file---->" + file);
		file.createNewFile();
		return file;
	}

	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 */
	public File creatSDDir(String dir) {
		File dirFile = new File(SDCardRoot + dir + File.separator);
		System.out.println(dirFile.mkdirs());
		return dirFile;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public boolean isFileExist(String fileName,String path){
		File file = new File(SDCardRoot + path + File.separator + fileName);
		return file.exists();
	}

	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 */
	public File write2SDFromInput(String path,String fileName,InputStream input){

		File file = null;
		OutputStream output = null;
		try{
			creatSDDir(path);
			file = createFileInSDCard(fileName, path);
			output = new FileOutputStream(file);
			byte buffer [] = new byte[4 * 1024];
			int temp ;
			while((temp = input.read(buffer)) != -1){
				output.write(buffer,0,temp);
			}
			output.flush();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
	
	
	public void writefile(String path,String fileName,String str )
	{
		FileOutputStream out;
		try {
			File file = new File(path);
			file.mkdirs();
			File fullfilepath = new File(path+ File.separator + fileName);
			System.out.println("file---->" + fullfilepath);
			fullfilepath.createNewFile();

//			//创建文件
//			file = new File(path);
//			file.createNewFile();
			
			//打开文件file 的OutputStream
			out = new FileOutputStream(fullfilepath);
			String infoToWrite = str;
			//将字符串转换成byte 数组写入文件
			out.write(infoToWrite.getBytes());
			//关闭文件file 的OutputStream
			out.close();
		} catch (IOException e) {
			//将出错信息打印到Logcat
			e.printStackTrace();
		}
	}
}
